package web

import (
	"local/config"

	"github.com/gin-gonic/gin"
)

func ConfigGet(c *gin.Context) {
	cfg := config.GetConfig()
	c.JSON(200, cfg)
}

func ConfigSet(c *gin.Context) {
	var newConfig config.Config
	if err := c.BindJSON(&newConfig); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := config.UpdateConfig(newConfig); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, gin.H{"message": "配置更新成功"})
}

func ChangePassword(c *gin.Context) {
	var json struct {
		OldPassword string `json:"oldPassword"`
		NewPassword string `json:"newPassword"`
	}
	if err := c.BindJSON(&json); err != nil {
		c.JSON(400, gin.H{"error": "无效的请求"})
		return
	}

	if !validateAdminPassword(json.OldPassword) {
		c.JSON(401, gin.H{"error": "原密码错误"})
		return
	}

	if json.NewPassword == "" {
		c.JSON(400, gin.H{"error": "新密码不能为空"})
		return
	}
	if json.NewPassword == json.OldPassword {
		c.JSON(400, gin.H{"error": "新密码不能与原密码相同"})
		return
	}

	if err := SaveAdminPassword(json.NewPassword); err != nil {
		c.JSON(500, gin.H{"error": "保存密码失败"})
		return
	}

	c.JSON(200, gin.H{"message": "密码修改成功"})
}
